/**
 * Created with WebStrom 10.0.3
 * User: 董豪超
 * Version:1.0.0
 * Date: 2016/08/04
 * Time: 16:48
 * Description:
 *
 *
 */

var AV = require('leanengine');
var async = require('async');
var session = require('express-session');

function Prize(prize){

}
module.exports=Prize;

//根据用户随机抽取奖品
Prize.getPrizeByUserID=function(UserID,callback){

    var fc=function(err,List){
        if(List.length>0){

            console.log("本级奖品的种类："+List.length);
            var index=Math.floor(Math.random()*List.length);
            console.log("同一奖品中的随机角标  "+index);
            console.log(List[index].get("Prize_Name"));



            callback(null,List[index]);
        }else{
            Prize.getPrizePercent(fc);
            console.log('没有抽中，进行系统再次抽取\r\n');
        }
    };

    Prize.getPrizePercent(fc);
};

//获得被抽中的奖品
Prize.getPrizePercent = function(callback){
    var query=new AV.Query("Prize");
    query.greaterThan("remain_num",0);

    Prize.getPercentRandom(function(err,PercentNum){
        console.log("出现的概率：  "+PercentNum);
        query.equalTo("Prize_Level",PercentNum);

        query.find().then(function(List){

            console.log(List.length);
            callback(null,List)
        },function(err){
            console.log(err);
            callback(err)
        });
    })
};

//奖品出现的概率
Prize.getPercentRandom=function(callback){
    var GaiLv = Math.random();//出现概率
    GaiLv = GaiLv.toFixed(2);
    GaiLv = GaiLv * 100;
    console.log("奖品概率："+GaiLv);

    var query = new AV.Query('Winning_Probability');
    query.lessThanOrEqualTo('In_val', GaiLv);
    query.greaterThanOrEqualTo('end_val', GaiLv);

    query.first().then(function (results) {
        console.log('得到的奖品等级：' + results.get('ret_val'));
        callback(null,results.get('ret_val'))
    }, function (error) {
    });
};




